import { getLoginApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '' // 用户的token
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
  },
  removeToken(state) {
    state.token = ''
    // 清除浏览器缓存token
    removeToken()
  }
}
const actions = {
  // 走登录接口
  async getlogin({ commit }, data) {
    // 发送请求获取token
    const res = await getLoginApi(data)
    // 提交mutation，将token存到state中
    commit('setToken', res.data.token)
    setToken(res.data.token)
    return res
  },

  // 退出登录方法
  logout({ commit }) {
    commit('removeToken')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
